/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bt;

import java.util.*;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

//test 
/** 
 *
 * @author kszyh
 */
public class BTClient extends TimerTask implements CommandListener {

    private static final int MAX_BAR_VALUE = 50;
    private static final int TIMER_FREQUENCY = 100;
    private final String serviceUUID = "8b9602b38b854a339ca4b79463ec4949";
    private final String connectionParameters = ";authorize=false;authenticate=false;encrypt=false";
    Midlet midlet;
    private Gauge postep;
    private StringItem napis1;
    private Timer taskTimer;
    private LocalDevice localDevice;
    private StreamConnectionNotifier notifier;
    private String localName;
    private int poprzedniTrybWykrywania = -1;

    public BTClient(Midlet _midlet) {
        midlet = _midlet;
        postep = new Gauge("Oczekiwanie na połączenie...", false, MAX_BAR_VALUE, 0);
        postep.setLayout(Gauge.LAYOUT_EXPAND);// tyle co 'na calej szerokosci;'
        postep.setLayout(Gauge.LAYOUT_CENTER);// tyle co 'na srodku';
        Command cmStop = new Command("Anuluj", Command.CANCEL, 1);
        Form form1 = new Form("");
        //form1.append(napis1);
        form1.append(postep);
        napis1 = new StringItem("","");
        form1.append(napis1);
        form1.addCommand(cmStop);

        form1.setCommandListener(this);
        midlet.getDisplay().setCurrent(form1);

        taskTimer = new Timer();
        taskTimer.scheduleAtFixedRate(this, 0, TIMER_FREQUENCY);

        try {
            localDevice = LocalDevice.getLocalDevice();
        } catch (Exception e) {
            localDevice = null;
            return;
        }

        try {
            localName = LocalDevice.getLocalDevice().getFriendlyName();
            saveDiscoverability();
            localDevice.setDiscoverable(DiscoveryAgent.LIAC);
        } catch (BluetoothStateException ex) {
            return;
        }

        AcceptAndOpenThread t = new AcceptAndOpenThread();
        t.start();

    }

    private void saveDiscoverability() {
        try {
            poprzedniTrybWykrywania = LocalDevice.getLocalDevice().getDiscoverable();
        } catch (Exception e) {
        }
    }

    private void restoreDiscoverability() {
        try {
            if (poprzedniTrybWykrywania != -1) {
                localDevice.setDiscoverable(poprzedniTrybWykrywania);
            }
        } catch (Exception e) {
        }

    }

    public void run() {
        int time = postep.getValue() + 1;
        if (time > postep.getMaxValue()) {
            time = 0;
        }
        postep.setValue(time);
    }

    protected void stop() {
        cancel();
        taskTimer.cancel();
    }

    public void connectionDiscoveryFinished(BluetoothConnection btConnection) {
        restoreDiscoverability();
        if (btConnection == null) {
            stop();
            midlet.startMIDlet();
        } else {
            stop();
        }
        midlet.getRec(btConnection);
        midlet.switchDisplayable(null, midlet.getKlient());


    }

    public void commandAction(Command c, Displayable d) {
        switch (c.getCommandType()) {
            case Command.CANCEL:
                closeNotifier();
                stop();
                restoreDiscoverability();
                midlet.startMIDlet();
                break;

        }
    }

    synchronized private void closeNotifier() {
        if (notifier != null) {
            try {
                notifier.close();
            } catch (Exception e) {
                notifier = null;
            }
        }
    }

    private class AcceptAndOpenThread extends Thread{
        public void run(){
            BluetoothConnection btConnection;

            try{
                notifier = (StreamConnectionNotifier) Connector.open("btspp://localhost:" + serviceUUID + ";name="+ localName + connectionParameters);
                StreamConnection streamConnection = (StreamConnection)notifier.acceptAndOpen();
                btConnection = new BluetoothConnection(streamConnection, localName, "Host");
                } catch(Exception e){
                    btConnection = null;
                }
            closeNotifier();
            connectionDiscoveryFinished(btConnection);
        }
    }
}
